package com.wang.designPattern.singleton;

/**
 * @description 双重锁单例
 * @Author wangzilong
 * @Date 2025/1/6 8:28
 */
public class DCLSingleton {
    // 使用volatile 避免指令重排
    private static volatile DCLSingleton instance;

    private DCLSingleton() {
        if (instance != null) {
            throw new RuntimeException("单例已被创建");
        }
        instance = this;
    }

    public static DCLSingleton getInstance() {
        if (instance == null) {
            synchronized (DCLSingleton.class) {
                // 避免多线程情况下，多个线程同时创建对象（防止抢锁失败陷入阻塞的线程，被再次唤醒后再次创建一个对象实例）
                if (instance == null) {
                    instance = new DCLSingleton();
                }
            }
        }
        return instance;
    }
}
